<template>
  <div class="login-container">
    <el-card class="login-card">
      <el-form @submit.native.prevent="login">
        <el-form-item
          ><div style="text-align:center">
            <h3>红绿灯二手车欢迎你</h3>
          </div></el-form-item
        >
        <el-form-item label="用户名">
          <el-input v-model="model.name"> </el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="model.pass"> </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" round>登录</el-button>
          <el-button type="success" circle
            ><router-link to="/register" tag="div">注册</router-link></el-button
          >
          <div style="text-align:right" class="mr-2">
            <el-button type="warning" plain circle><router-link to="/home" tag="div">
            返回首页</router-link></el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style>
.login-card {
  width: 30rem;
  margin: 9rem auto;
}
</style>
<script>
export default {
  data() {
    return {
      model: {},
    };
  },
  methods: {
    async login() {
      await this.$http.post("login", this.model).then((data) => {
        console.log("我在这里" + data.token);
        // 将username 存 sessionStorage 中 用户关闭窗口数据就会丢失，需要再次登录
        // 将username 存 localStorage 中 用户关闭窗口数也不会丢失
        sessionStorage.username = data.user.name;
        sessionStorage.userid=data.user._id;
        console.log(sessionStorage.userid);
        localStorage.token = data.token;

        this.$router.go(-1);
        console.group("login");
        console.log(data);
        console.groupEnd();
        return data;
      });
      this.$message({
        type: "success",
        message: "登录成功",
        // 等待0.8s弹窗关闭
        duration: 800,
      });
    },
  },
};
</script>
